package utils;

import cn.hutool.core.date.DateUtil;
import org.junit.jupiter.api.Assertions;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


public class MyTestLogToTxt {

    /**
     * 创建文件
     */
    private File creatFile() throws IOException {
        File file = new File("MyTestResultLog.txt");
        Assertions.assertTrue(file.exists() || file.createNewFile());

        return file;
    }

    /**
     * 初始化
     */
    public void initLogFile() {
        File file = new File("MyTestResultLog.txt");
        if (file.exists()) {
            if (!file.delete()) {
                throw new RuntimeException("删除文件失败");
            }
        }
    }

    public void printLogs(String number, String exeception) {
        try {
            FileWriter fw = new FileWriter(creatFile(), true);
            BufferedWriter bufferedWriter = new BufferedWriter(fw);
            bufferedWriter.write(DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"));
            bufferedWriter.newLine();
            bufferedWriter.write("用例编号：" + number);
            bufferedWriter.newLine();
            if (exeception != null) {
                bufferedWriter.write(exeception);
                bufferedWriter.newLine();
            }
            bufferedWriter.flush();
            fw.close();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 输出日志
     */
    public void printLogs(String number, String serverPath, String requestDatas, String method, int responseCode,String response, String responsetime) throws IOException {

        FileWriter fw = new FileWriter(creatFile(), true);
        BufferedWriter bufferedWriter = new BufferedWriter(fw);
        bufferedWriter.write(DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"));
        bufferedWriter.newLine();
        bufferedWriter.write("用例编号：" + number);
        bufferedWriter.newLine();

        bufferedWriter.write("请求：" + method + "	");
        bufferedWriter.write(serverPath);
        bufferedWriter.newLine();

        bufferedWriter.write("请求参数：" + requestDatas);
        bufferedWriter.newLine();
        bufferedWriter.write("响应码：" + responseCode);
        bufferedWriter.newLine();
        bufferedWriter.write("响应参数：" + response);
        bufferedWriter.newLine();
        bufferedWriter.write("响应耗时：" + responsetime);
        bufferedWriter.newLine();
        bufferedWriter.newLine();

        bufferedWriter.flush();

        fw.close();
        bufferedWriter.close();
    }

}